// 修改React导入语句，添加useEffect
import React, { useState, useEffect } from 'react';
// 修改导入语句，添加Checkbox组件
import { Form, Input, Button, Card, message, Typography, Radio, Space, Upload, Steps, Checkbox } from 'antd';
import { UserOutlined, LockOutlined, PhoneOutlined, UserAddOutlined, UploadOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import { userService } from '../services/userService';
import type { RegisterData } from '../services/userService';
import '../App.css';

const { Title, Text } = Typography;
const { Step } = Steps;
const { Dragger } = Upload;

const Register: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [currentStep, setCurrentStep] = useState(1);
  const [userType, setUserType] = useState<'jobseeker' | 'employer'>('jobseeker');
  const navigate = useNavigate();
  const [form] = Form.useForm();

  // 检查表单数据是否已保存
  useEffect(() => {
    const savedForm = localStorage.getItem('registerForm');
    if (savedForm) {
      try {
        const parsedForm = JSON.parse(savedForm);
        form.setFieldsValue(parsedForm);
        setUserType(parsedForm.userType || 'jobseeker');
        // 可以根据保存的数据恢复到相应步骤
      } catch (e) {
        console.error('Failed to parse saved form data', e);
      }
    }
  }, [form]);

  // 保存表单数据到localStorage
  const saveFormData = () => {
    const formValues = form.getFieldsValue();
    localStorage.setItem('registerForm', JSON.stringify(formValues));
  };

  const handleUserTypeChange = (value: 'jobseeker' | 'employer') => {
    setUserType(value);
    saveFormData();
  };

  const handleNextStep = () => {
    // 验证当前步骤的必填字段
    const requiredFields = currentStep === 1 
      ? ['fullName', 'email', 'phone', 'password']
      : userType === 'jobseeker' 
        ? ['position', 'education', 'experience']
        : ['companyName', 'companyType', 'companySize', 'companyLocation', 'companyDescription', 'contactPosition', 'businessLicense', 'organizationCode', 'legalIdCard'];
    
    const formValues = form.getFieldsValue();
    const isValid = requiredFields.every(field => formValues[field]);
    
    if (!isValid) {
      message.warning('请填写完整所有必填项');
      return;
    }
    
    saveFormData();
    setCurrentStep(currentStep + 1);
  };

  const handlePrevStep = () => {
    if (currentStep > 1) {
      setCurrentStep(currentStep - 1);
    }
  };

  const handleRegister = async () => {
    setLoading(true);
    try {
      const formValues = form.getFieldsValue();
      
      // 准备注册数据
      const registerData: RegisterData = {
        email: formValues.email,
        password: formValues.password,
        fullName: formValues.fullName,
        phone: formValues.phone,
        userType: formValues.userType,
        
        // 招聘方字段
        companyName: formValues.companyName,
        companyType: formValues.companyType,
        companySize: formValues.companySize,
        companyLocation: formValues.companyLocation,
        companyDescription: formValues.companyDescription,
        companyWebsite: formValues.companyWebsite,
        contactPosition: formValues.contactPosition,
        businessLicenseId: formValues.businessLicenseId,
        organizationCodeId: formValues.organizationCodeId,
        legalIdCardId: formValues.legalIdCardId,
        verificationStatus: 'pending', // 初始状态设为待审核
        
        // 求职者字段
        position: formValues.position,
        education: formValues.education,
        experience: formValues.experience,
        skills: formValues.skills,
        resumeId: formValues.resumeId
      };
      
      const response = await userService.register(registerData);
      
      // 根据用户类型显示不同的成功消息
      if (userType === 'employer') {
        message.success(response.message || '注册成功！您的企业信息将在审核通过后生效，请耐心等待。');
      } else {
        message.success(response.message || '注册成功，请登录');
      }
      
      // 清除保存的表单数据
      localStorage.removeItem('registerForm');
      navigate('/login');
    } catch (error) {
      message.error('注册失败，请稍后重试');
    } finally {
      setLoading(false);
    }
  };

  const steps = [
    { title: '基本信息', description: '填写账号基本信息' },
    { title: '详细资料', description: userType === 'jobseeker' ? '填写求职相关信息' : '填写企业相关信息' },
    { title: '完成注册', description: '确认并提交注册' }
  ];

  return (
    <div style={{ 
      minHeight: '100vh', 
      display: 'flex', 
      alignItems: 'center', 
      justifyContent: 'center',
      padding: '20px',
      background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)'
    }}>
      <Card 
        style={{ 
          width: 600, 
          boxShadow: '0 10px 30px rgba(0,0,0,0.1)',
          borderRadius: '12px',
          overflow: 'hidden'
        }}
      >
        <div style={{ textAlign: 'center', marginBottom: 24 }}>
          <Title level={2} style={{ color: '#1890ff', marginBottom: 8 }}>注册账号</Title>
          <Text type="secondary">创建您的求职管理系统账号</Text>
        </div>
        
        {/* 步骤指示器 */}
        <Steps current={currentStep - 1} items={steps} style={{ marginBottom: 24 }} />
        
        <Form
          form={form}
          name="register"
          layout="vertical"
          onChange={saveFormData}
        >
          {/* 步骤1：基本信息 */}
          {currentStep === 1 && (
            <>
              {/* 用户类型选择 */}
              <Form.Item
                name="userType"
                label="用户类型"
                rules={[{ required: true, message: '请选择用户类型' }]}
              >
                <Radio.Group 
                  value={userType} 
                  onChange={(e) => handleUserTypeChange(e.target.value)}
                  buttonStyle="solid"
                  style={{ width: '100%' }}
                >
                  <Radio.Button value="jobseeker">求职者</Radio.Button>
                  <Radio.Button value="employer">招聘方</Radio.Button>
                </Radio.Group>
              </Form.Item>
              
              <Form.Item
                name="fullName"
                label="姓名"
                rules={[{ required: true, message: '请输入姓名' }]}
              >
                <Input
                  prefix={<UserAddOutlined className="site-form-item-icon" />}
                  placeholder="请输入您的姓名"
                  size="large"
                />
              </Form.Item>
              
              <Form.Item
                name="email"
                label="邮箱"
                rules={[
                  { required: true, message: '请输入邮箱地址' },
                  { type: 'email', message: '请输入有效的邮箱地址' },
                ]}
              >
                <Input
                  prefix={<UserOutlined className="site-form-item-icon" />}
                  placeholder="请输入邮箱地址"
                  size="large"
                />
              </Form.Item>
              
              <Form.Item
                name="phone"
                label="手机号"
                rules={[
                  { required: true, message: '请输入手机号' },
                  { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号码' }
                ]}
              >
                <Input
                  prefix={<PhoneOutlined className="site-form-item-icon" />}
                  placeholder="请输入手机号"
                  size="large"
                />
              </Form.Item>
              
              <Form.Item
                name="password"
                label="密码"
                rules={[
                  { required: true, message: '请设置密码' },
                  { min: 6, message: '密码至少需要6个字符' },
                  { pattern: /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d@$!%*#?&]{6,}$/, 
                    message: '密码必须包含字母和数字' }
                ]}
              >
                <Input.Password
                  prefix={<LockOutlined className="site-form-item-icon" />}
                  placeholder="请设置密码"
                  size="large"
                  visibilityToggle
                />
              </Form.Item>
            </>
          )}
          
          {/* 步骤2：详细资料 */}
          {currentStep === 2 && (
            <>
              {userType === 'jobseeker' ? (
                // 求职者详细信息
                <>
                  <Form.Item
                    name="position"
                    label="期望职位"
                    rules={[{ required: true, message: '请输入期望职位' }]}
                  >
                    <Input placeholder="如：前端开发工程师" size="large" />
                  </Form.Item>
                  
                  <Form.Item
                    name="education"
                    label="最高学历"
                    rules={[{ required: true, message: '请输入最高学历' }]}
                  >
                    <Input placeholder="如：本科" size="large" />
                  </Form.Item>
                  
                  <Form.Item
                    name="experience"
                    label="工作经验"
                    rules={[{ required: true, message: '请输入工作经验' }]}
                  >
                    <Input placeholder="如：3年" size="large" />
                  </Form.Item>
                  
                  <Form.Item
                    name="skills"
                    label="技能特长"
                  >
                    <Input placeholder="如：React, TypeScript, Node.js" size="large" />
                  </Form.Item>
                  
                  <Form.Item
                    name="resume"
                    label="上传简历"
                  >
                    <Dragger name="resume" beforeUpload={() => false}>
                      <p className="ant-upload-drag-icon">
                        <UploadOutlined />
                      </p>
                      <p className="ant-upload-text">点击或拖拽文件到此区域上传</p>
                      <p className="ant-upload-hint">
                        支持 .pdf, .doc, .docx 格式文件，大小不超过5MB
                      </p>
                    </Dragger>
                  </Form.Item>
                </>
              ) : (
                // 招聘方详细信息
                <>
                  <Form.Item
                    name="companyName"
                    label="公司名称"
                    rules={[{ required: true, message: '请输入公司名称' }]}
                  >
                    <Input placeholder="请输入公司全称" size="large" />
                  </Form.Item>
                  
                  <Form.Item
                    name="companyType"
                    label="公司类型"
                    rules={[{ required: true, message: '请输入公司类型' }]}
                  >
                    <Input placeholder="如：互联网、金融、教育等" size="large" />
                  </Form.Item>
                  
                  <Form.Item
                    name="companySize"
                    label="公司规模"
                    rules={[{ required: true, message: '请输入公司规模' }]}
                  >
                    <Input placeholder="如：50-100人" size="large" />
                  </Form.Item>
                  
                  <Form.Item
                    name="companyLocation"
                    label="公司地址"
                    rules={[{ required: true, message: '请输入公司地址' }]}
                  >
                    <Input placeholder="请输入详细地址" size="large" />
                  </Form.Item>
                  
                  <Form.Item
                name="companyDescription"
                label="公司简介"
                rules={[{ required: true, message: '请输入公司简介' }]}
              >
                <Input.TextArea rows={4} placeholder="请简要介绍公司的主营业务、发展历程等" size="large" />
              </Form.Item>
              
              <Form.Item
                name="companyWebsite"
                label="公司网站"
                rules={[{ type: 'url', message: '请输入有效的网址' }]}
              >
                <Input placeholder="如：https://www.example.com" size="large" />
              </Form.Item>
              
              <Form.Item
                name="contactPosition"
                label="联系人职位"
                rules={[{ required: true, message: '请输入联系人在公司的职位' }]}
              >
                <Input placeholder="如：人力资源经理、招聘总监" size="large" />
              </Form.Item>
              
              {/* 文件上传审核区域 */}
              <div style={{ marginTop: 16, padding: 16, backgroundColor: '#f9f9f9', borderRadius: 8, border: '1px solid #eee' }}>
                <Typography.Text type="warning" strong style={{ display: 'block', marginBottom: 16 }}>
                  【重要】为确保企业信息真实性，需上传以下资质文件进行审核
                </Typography.Text>
                
                <Form.Item
                  name="businessLicense"
                  label="营业执照上传"
                  rules={[{ required: true, message: '请上传营业执照扫描件或照片' }]}
                >
                  <Dragger name="license" beforeUpload={() => false}>
                    <p className="ant-upload-drag-icon">
                      <UploadOutlined />
                    </p>
                    <p className="ant-upload-text">点击或拖拽营业执照到此区域上传</p>
                    <p className="ant-upload-hint">
                      支持 .jpg, .png, .pdf 格式，大小不超过10MB，需确保文字清晰可见
                    </p>
                  </Dragger>
                </Form.Item>
                
                <Form.Item
                  name="organizationCode"
                  label="组织机构代码证上传"
                  rules={[{ required: true, message: '请上传组织机构代码证扫描件或照片' }]}
                >
                  <Dragger name="orgCode" beforeUpload={() => false}>
                    <p className="ant-upload-drag-icon">
                      <UploadOutlined />
                    </p>
                    <p className="ant-upload-text">点击或拖拽组织机构代码证到此区域上传</p>
                    <p className="ant-upload-hint">
                      支持 .jpg, .png, .pdf 格式，大小不超过10MB
                    </p>
                  </Dragger>
                </Form.Item>
                
                <Form.Item
                  name="legalIdCard"
                  label="法人身份证上传"
                  rules={[{ required: true, message: '请上传法人身份证正反面照片' }]}
                >
                  <Dragger name="idCard" beforeUpload={() => false}>
                    <p className="ant-upload-drag-icon">
                      <UploadOutlined />
                    </p>
                    <p className="ant-upload-text">点击或拖拽法人身份证正反面照片到此区域上传</p>
                    <p className="ant-upload-hint">
                      支持 .jpg, .png 格式，大小不超过10MB，需确保证件信息清晰可见
                    </p>
                  </Dragger>
                </Form.Item>
                
                <Form.Item
                  name="companyProfile"
                  label="企业形象照片"
                >
                  <Upload.Dragger name="profile" multiple beforeUpload={() => false}>
                    <p className="ant-upload-drag-icon">
                      <UploadOutlined />
                    </p>
                    <p className="ant-upload-text">点击或拖拽企业办公环境、团队照片等到此区域上传</p>
                    <p className="ant-upload-hint">
                      支持 .jpg, .png 格式，最多上传5张，每张不超过5MB
                    </p>
                  </Upload.Dragger>
                </Form.Item>
                
                <Typography.Text type="secondary" style={{ display: 'block', marginTop: 16 }}>
                  注：所有上传文件仅用于企业资质审核，我们将严格保护您的信息安全。审核通常在1-3个工作日内完成。
                </Typography.Text>
              </div>
                </>
              )}
            </>
          )}
          
          {/* 步骤3：完成注册 */}
          {currentStep === 3 && (
            <div>
              <Title level={5} style={{ marginBottom: 16 }}>注册信息确认</Title>
              
              <div style={{ padding: 16, backgroundColor: '#f5f5f5', borderRadius: 8, marginBottom: 24 }}>
                <div style={{ marginBottom: 8 }}>
                  <Text strong>用户类型：</Text>
                  <Text>{userType === 'jobseeker' ? '求职者' : '招聘方'}</Text>
                </div>
                <div style={{ marginBottom: 8 }}>
                  <Text strong>姓名：</Text>
                  <Text>{form.getFieldValue('fullName')}</Text>
                </div>
                <div style={{ marginBottom: 8 }}>
                  <Text strong>邮箱：</Text>
                  <Text>{form.getFieldValue('email')}</Text>
                </div>
                <div style={{ marginBottom: 8 }}>
                  <Text strong>手机号：</Text>
                  <Text>{form.getFieldValue('phone')}</Text>
                </div>
                
                {userType === 'jobseeker' && (
                  <>
                    <div style={{ marginBottom: 8 }}>
                      <Text strong>期望职位：</Text>
                      <Text>{form.getFieldValue('position')}</Text>
                    </div>
                    <div style={{ marginBottom: 8 }}>
                      <Text strong>最高学历：</Text>
                      <Text>{form.getFieldValue('education')}</Text>
                    </div>
                  </>
                )}
                
                {userType === 'employer' && (
                  <>
                    <div style={{ marginBottom: 8 }}>
                      <Text strong>公司名称：</Text>
                      <Text>{form.getFieldValue('companyName')}</Text>
                    </div>
                    <div style={{ marginBottom: 8 }}>
                      <Text strong>公司类型：</Text>
                      <Text>{form.getFieldValue('companyType')}</Text>
                    </div>
                    <div style={{ marginBottom: 8 }}>
                      <Text strong>公司规模：</Text>
                      <Text>{form.getFieldValue('companySize')}</Text>
                    </div>
                    <div style={{ marginBottom: 8 }}>
                      <Text strong>公司地址：</Text>
                      <Text>{form.getFieldValue('companyLocation')}</Text>
                    </div>
                    <div style={{ marginBottom: 8 }}>
                      <Text strong>公司简介：</Text>
                      <Text>{form.getFieldValue('companyDescription')}</Text>
                    </div>
                    <div style={{ marginBottom: 8 }}>
                      <Text strong>公司网站：</Text>
                      <Text>{form.getFieldValue('companyWebsite') || '未填写'}</Text>
                    </div>
                    <div style={{ marginBottom: 8 }}>
                      <Text strong>联系人职位：</Text>
                      <Text>{form.getFieldValue('contactPosition')}</Text>
                    </div>
                    <div style={{ marginBottom: 8 }}>
                      <Text strong>营业执照：</Text>
                      <Text type="success">已上传</Text>
                    </div>
                    <div style={{ marginBottom: 8 }}>
                      <Text strong>组织机构代码证：</Text>
                      <Text type="success">已上传</Text>
                    </div>
                    <div style={{ marginBottom: 8 }}>
                      <Text strong>法人身份证：</Text>
                      <Text type="success">已上传</Text>
                    </div>
                    <div style={{ marginTop: 16, padding: 8, backgroundColor: '#fff7e6', borderRadius: 4, border: '1px solid #ffd591' }}>
                      <Text type="warning" strong>注册须知：</Text>
                      <Text type="secondary">
                        提交注册后，您的企业资质信息将进入审核流程，审核通过后账户才能正常使用完整功能。审核结果将通过邮件通知您。
                      </Text>
                    </div>
                  </>
                )}
              </div>
              
              <Form.Item name="agreement" valuePropName="checked" rules={[{ required: true, message: '请阅读并同意用户协议' }]}>
                <Space direction="vertical" style={{ textAlign: 'left' }}>
                  <Checkbox>
                    我已阅读并同意
                    <a href="#">《用户协议》</a>
                    和
                    <a href="#">《隐私政策》</a>
                  </Checkbox>
                  {userType === 'employer' && (
                    <Checkbox>
                      我确认所提供的企业资质信息真实有效，并同意平台进行审核
                    </Checkbox>
                  )}
                  {userType === 'employer' && (
                    <Checkbox>
                      我了解企业认证审核流程，将耐心等待审核结果
                    </Checkbox>
                  )}
                </Space>
              </Form.Item>
            </div>
          )}
          
          {/* 底部按钮 */}
          <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 24 }}>
            {currentStep > 1 && (
              <Button onClick={handlePrevStep}>
                上一步
              </Button>
            )}
            
            <div style={{ marginLeft: 'auto' }}>
              {currentStep < 3 ? (
                <Button type="primary" onClick={handleNextStep}>
                  下一步
                </Button>
              ) : (
                <Button
                  type="primary"
                  onClick={handleRegister}
                  loading={loading}
                  style={{ width: 200 }}
                >
                  完成注册
                </Button>
              )}
            </div>
          </div>
        </Form>
      </Card>
    </div>
  );
};

export default Register;